//
//  FeedBackDetailViewController.m
//  fitnessmanage
//
//  Created by wujian on 2017/12/18.
//  Copyright © 2017年 zongquankeji. All rights reserved.
//

#import "FeedBackDetailViewController.h"
#import "BRPlaceholderTextView.h"
#import "ZLPhotoPickerViewController.h"
#import "UIImage+ZLPhotoLib.h"
#import "ZLPhotoPickerBrowserPhoto.h"
#import "EditClassCoverImageCollectionViewCell.h"
#import "MyViewController.h"

@interface FeedBackDetailViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,DeleteCoverImage>

@property(nonatomic,weak)UICollectionView *collectionView;

@property (nonatomic , strong) ZLPhotoPickerBrowserPhoto *photo;

@property(nonatomic,strong)NSMutableArray *dataSource;

@property(nonatomic,weak)BRPlaceholderTextView *textView;

@property(nonatomic,weak)UIView *whitView;

@end

@implementation FeedBackDetailViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
 
    [self createSubView];
    
    UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(rightBtnClick)];
    
    [rightButtonItem setTitleTextAttributes:@{NSForegroundColorAttributeName:CSBlackColor,NSFontAttributeName:MidFont} forState:UIControlStateNormal];
    
    self.navigationItem.rightBarButtonItem = rightButtonItem;
}

-(void)createSubView{
    
    self.view.backgroundColor = BackGroundColor;
    
    UIScrollView *scrollView = [[UIScrollView alloc] init];
    [self.view addSubview:scrollView];
    [scrollView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
    
    UIView *whiteView = [[UIView alloc] init];
    whiteView.backgroundColor = CSWhiteColor;
    [scrollView addSubview:whiteView];
    [whiteView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.left.width.mas_equalTo(scrollView);
    }];
    
    self.whitView = whiteView;
    
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.font = MidBigFont;
    titleLabel.text = @"问题和意见";
    [whiteView addSubview:titleLabel];
    [titleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.left.mas_equalTo(whiteView).offset(15);
    }];
    
    UIView *lineView = [[UIView alloc] init];
    lineView.backgroundColor = LineBackGroundColor;
    [whiteView addSubview:lineView];
    [lineView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(titleLabel.mas_bottom).offset(15);
        make.left.mas_equalTo(titleLabel);
        make.height.mas_equalTo(1);
        make.right.mas_equalTo(whiteView);
    }];
    
    BRPlaceholderTextView *textView = [[BRPlaceholderTextView alloc] init];
    textView.placeholder = @"请详细描述您使用时遇到的问题和建议，为更好更快的解决问题可上传页面截图";
    textView.font = MidBigFont;
    [whiteView addSubview:textView];
    self.textView = textView;
    [textView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(titleLabel);
        make.top.mas_equalTo(lineView.mas_bottom).offset(20);
        make.right.mas_equalTo(whiteView);
        make.height.mas_equalTo(100);
    }];
    
    
    UIView *lineView1 = [[UIView alloc] init];
    lineView1.backgroundColor = LineBackGroundColor;
    [whiteView addSubview:lineView1];
    [lineView1 mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(textView.mas_bottom);
        make.left.width.height.mas_equalTo(lineView);
    }];
    
    UILabel *addLabel = [[UILabel alloc] init];
    addLabel.font = MidBigFont;
    addLabel.text = @"添加图片(选填，可提供问题截图)";
    [whiteView addSubview:addLabel];
    [addLabel mas_remakeConstraints:^(MASConstraintMaker *make) {       
        make.left.mas_equalTo(titleLabel);
        make.top.mas_equalTo(lineView1.mas_bottom).offset(15);
        make.bottom.mas_equalTo(whiteView);
    }];
    
    
    
    /**
     CollectionView
     */
    UICollectionViewFlowLayout *collectViewFlowLayout = [[UICollectionViewFlowLayout alloc] init];
    //设置cell之间间距
    collectViewFlowLayout.minimumInteritemSpacing = 3;
    //设置行距
    collectViewFlowLayout.minimumLineSpacing = 10;
    
    collectViewFlowLayout.sectionInset = UIEdgeInsetsMake(20, 15, 20, 15);
    
    CGFloat itemWith = ( SCREEN_WIDTH - 10 * 2 - 30) / 3;
    //设置Item大小
    collectViewFlowLayout.itemSize = CGSizeMake(itemWith, itemWith);
    UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:collectViewFlowLayout];
    collectionView.showsHorizontalScrollIndicator = NO;
    collectionView.showsVerticalScrollIndicator = NO;
    collectionView.backgroundColor = CSWhiteColor;
    collectionView.delegate = self;
    collectionView.dataSource = self;
    [collectionView registerClass:[EditClassCoverImageCollectionViewCell class] forCellWithReuseIdentifier:@"EditClassCoverImageCollectionViewCell"];
    [self.view addSubview:collectionView];
    [collectionView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(whiteView.mas_bottom);
        
        make.left.width.mas_equalTo(self.view);
        
        make.height.mas_equalTo(itemWith + 30);
    }];
    
    self.collectionView = collectionView;
    
    /**
     确认按钮
     */
    UIButton *sureBtn = [[UIButton alloc] init];
    [sureBtn setTitle:@"确定"];
    [sureBtn setTitleColor:CSColorFromRGB(0x0a0a0a)];
    sureBtn.titleLabel.font = MidBigFont;
    sureBtn.backgroundColor = ButtonBackGroundColor;
    [scrollView addSubview:sureBtn];
}

#pragma mark UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    
    return self.dataSource.count + 1;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    EditClassCoverImageCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"EditClassCoverImageCollectionViewCell" forIndexPath:indexPath];
    
    if (indexPath.row == self.dataSource.count) {
        
        cell.isLast = YES;
    }
    else{
        
        NSString *urlStr = [NSString stringWithFormat:@"%@%@",[self.dataSource objectAtIndex:indexPath.row],mid_image];
        
        urlStr=[urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        
        [cell.courseImageView sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:PlaceHold];
        
        cell.selectRow = indexPath.row;
        
        cell.deleteCoverImage = self;
        
        cell.isLast = NO;
    }
    
    return cell;
}


#pragma mark UICollectionDelegate
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == self.dataSource.count) {
        
        if (self.dataSource.count == 5) {
            
            [MBProgressHUD showText:@"最多只能上传5张图片" toview:self.view];
            
            return;
        }
        
        [self photoSelect];
    }
    
}

#pragma mark DeleteCoverImage
-(void)deleteCoverImageWithRow:(NSInteger)row{
    
    [self.dataSource removeObjectAtIndex:row];
    
    [self.collectionView reloadData];
}

#pragma Logo图片选择
-(void)photoSelect{
    
    ZLPhotoPickerViewController *pickerVc = [[ZLPhotoPickerViewController alloc] init];
    
    pickerVc.maxCount = 1;
    
    // Jump AssetsVc
    pickerVc.status = PickerViewShowStatusCameraRoll;
    // Recoder Select Assets
    //    pickerVc.selectPickers = self.assets;
    // Filter: PickerPhotoStatusAllVideoAndPhotos, PickerPhotoStatusVideos, PickerPhotoStatusPhotos.
    
    pickerVc.photoStatus = PickerPhotoStatusPhotos;
    // Desc Show Photos, And Suppor Camera
    pickerVc.topShowPhotoPicker = YES;
    
    // CallBack
    __weak typeof(self)weakSelf = self;
    
    pickerVc.callBack = ^(NSArray<ZLPhotoAssets *> *status){
        
        for (ZLPhotoAssets *assets in status) {
            
            ZLPhotoPickerBrowserPhoto *photo = [ZLPhotoPickerBrowserPhoto photoAnyImageObjWith:assets];
            
            weakSelf.photo = photo;
            
            UIImage *image ;
            
            if ([weakSelf.photo.asset isKindOfClass:[UIImage class]]) {
                
                image = (UIImage *)weakSelf.photo.asset;
            }
            else{
                
                image = [weakSelf.photo.asset originImage];
            }
            
            [weakSelf uploadImage:image];
            
//            break;
        }
    };
    
    [pickerVc showPickerVc:self];
}

-(void)uploadImage:(UIImage *)image{
    
    
    NSData *imageData;
    
    
    
    imageData  = UIImageJPEGRepresentation(image,0.1);
    
    [MBProgressHUD showMessage:@"上传中.." toView:self.view];

    RAYUploader *upload = [RAYUploader defaultUploader];

    [upload uploadWithData:imageData complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {

        [MBProgressHUD hideHUDForView:self.view];

        if (key) {

            dispatch_async(dispatch_get_main_queue(), ^{

                NSString *picUrl = [NSString stringWithFormat:@"%@%@",QiNiuBase,key];

                [self.dataSource addObject:picUrl];

                self.photo = nil;

                if (self.dataSource.count >= 3) {

                    CGFloat itemWith = ( SCREEN_WIDTH - 10 * 2 - 30) / 3;

                    [self.collectionView mas_remakeConstraints:^(MASConstraintMaker *make) {

                        make.top.mas_equalTo(self.whitView.mas_bottom);
                        
                        make.left.width.mas_equalTo(self.view);

                        make.height.mas_equalTo(itemWith * 2+ 50);
                    }];
                }

                [self.collectionView reloadData];
            });

        }

    }];
    
}


#pragma mark 右侧按钮点击
-(void)rightBtnClick{
    
    //Post_SuggestionOperate
    
    NSString *content = self.textView.text;
    
    
    if ([content isEmptyString]) {
        
        [MBProgressHUD showText:@"请输入意见" toview:self.view];
        
        return;
    }
    
    [MBProgressHUD showMessage:@"请求中..." toView:self.view];
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    UserAccount *userAccount = [UserAccount account];
    
    [params setObject:self.title forKey:@"Title"];
    
    [params setObject:content forKey:@"Content"];
    
    [params setValue:[self.dataSource toJSONString] forKey:@"Pics"];
    
    [params setObject:userAccount.ID forKey:@"AddUserID"];
    
    [params setObject:userAccount.NickName forKey:@"AddUserName"];
    
    [HTTPTool POSTRaw:Post_SuggestionOperate parameters:params
     
              success:^(id responseObject){
                  
                  [MBProgressHUD hideHUDForView:self.view];
                  
                  if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0) {
                      
                      [MBProgressHUD showText:@"保存成功"];
                      
                      for (UIViewController *temp in self.navigationController.viewControllers) {
                          
                          if ([temp isKindOfClass:[MyViewController class]]) {
                              
                              [self.navigationController popToViewController:temp animated:YES];
                          }
                      }
                  }
                  
              }
     
              failure:^(NSError *error){
                  
                  [MBProgressHUD hideHUDForView:self.view];
              }];
}


#pragma mark Get--
-(NSMutableArray *)dataSource{
    
    if (!_dataSource) {
        
        _dataSource = [[NSMutableArray alloc] init];
    }
    
    return _dataSource;
}
@end
